package static

import (
	"embed"
	"io/fs"
	"net/http"
	"path"
	"strings"
)

type embedFileSystem struct {
	http.FileSystem
}

func (e embedFileSystem) Exists(prefix string, urlPath string) bool {
	if strings.HasPrefix(urlPath, prefix) {
		file := strings.TrimPrefix(urlPath, prefix)
		if urlPath == prefix || file == "" || file == "/" || file == "index" {
			file = "index.html"
		}
		_, err := e.Open(file)
		if err == nil {
			return true
		}
		if path.Ext(file) == "" {
			_, err = e.Open(file + ".html")
			if err == nil {
				return true
			}
		}
	}

	return false
}

func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem {
	fsys, err := fs.Sub(fsEmbed, targetPath)
	if err != nil {
		panic(err)
	}
	return embedFileSystem{
		FileSystem: http.FS(fsys),
	}
}
